<template>
  <div class="form-sparepart">
    <el-button type="primary" icon="el-icon-plus" @click="handleClickAdd">
      {{$t('common.base.add2')}}
    </el-button>

    <!-- 物料清单表单表格 S -->
    <el-table
      v-table-style
      :data="dataList"
      max-height="500"
      header-row-class-name="common-list-table-header__v2"
      border
      row-key="MID"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <!-- <el-table-column type="index" width="50" :label="$t('common.base.SN')" /> -->
      <el-table-column
        v-for="(column, index) in columns"
        :key="`${column.displayName}_${index}`"
        :prop="column.fieldName"
        :label="column.displayName"
        :min-width="column.minWidth || '108px'"
        :show-overflow-tooltip="!['num'].includes(column.fieldName)"
      >
        <template slot-scope="scope">
          <!-- 数量 -->
          <template v-if="column.fieldName === 'num'">
            <el-input-number
              class="table-blacklist"
              v-model="scope.row.num"
              step-strictly
              controls-position="right"
              :min="1"
              :max="999999"
            ></el-input-number>
          </template>
          <template v-else>
            {{
              $formatFormField(column, scope.row)
            }}
          </template>
        </template>
      </el-table-column>
      <el-table-column fixed="right" :label="$t('common.base.table.col.operator')" width="150">
        <template slot-scope="scope">
          <el-button 
            @click="changeOrder(scope.row)" 
            v-if="scope.row.level === 0"
            type="text"
          >
            {{$t('product.btns.adjustPriority')}}
          </el-button>
          <el-button
            type="text"
            size="small"
            v-if="scope.row.level === 0"
            @click="handleClickDelete(scope.row)"
          >
            {{$t('common.base.delete')}}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 物料清单表单表格 E -->

    <!-- 物料添加弹框 -->
    <material-dialog
      ref="materialDialogRef"
      :dataList="dataList"
      :columns="materialColumns"
      pageType="edit"
      @handleSubmit="handleSubmit"
    ></material-dialog>
    <order-material 
      ref="orderMaterial" 
      @save="saveOrder">
    </order-material>

  </div>
</template>

<script>
/* mixin */
import FormMixin from '@src/component/form/mixin/form';
import Platform from '@src/util/platform.ts';
import MaterialDialog from './MaterialDialog.vue';
import OrderMaterial from './OrderMaterial.vue';

export default {
  name: 'form-materials-bill-build',
  mixins: [FormMixin],
  props: {
    value: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      dataList: [],
    };
  },
  components: {
    MaterialDialog,
    OrderMaterial
  },
  computed: {
    columns() {
      let columns = [
        {
          displayName: this.$t('common.fields.orderNo.displayName'),
          fieldName: 'customIndex',
          setting: {
            originalFormType: 'text',
          },
        },
        ...(this.field?.subFormFieldList || []),
        {
          displayName: this.$t('product.materialFields.num.displayName'),
          fieldName: 'num',
          setting: {
            originalFormType: 'text',
          },
        },
      ];
      return columns;
    },
    materialColumns() {
      let columns = [...(this.field?.subFormFieldList || [])];
      return columns;
    },
  },
  watch: {
    value: {
      handler(newValue) {
        this.dataList = this.filterDuplicateData(newValue);
        this.setIndex(this.dataList);
        (this.dataList || []).forEach(item => {
          item.level = 0;
        });
      },
      immediate: true,
    },
  },
  methods: {
    changeOrder(row) {
      this.$refs.orderMaterial.open(row)
    },
    saveOrder({ row, number }) {
      if (number > this.dataList?.length) {
        number = this.dataList?.length;
      }
      this.setOrder(this.dataList, row, number);
      this.setIndex(this.dataList);
      this.inputForValue(this.dataList);
    },
    setOrder(trees, row, number) {
      if(!trees) return;
      for (let i = 0; i < trees.length; i++) {
        if (trees[i].MID === row.MID) {
          // const currentIndex = trees.findIndex(item => item.MID === row.MID);
          if (number > trees.length) number = trees.length;
          trees.splice(i, 1);
          trees.splice(number - 1, 0, row);
          break;
        }
        if (trees[i].children && trees[i].children.length > 0) {
          this.setOrder(trees[i].children, row, number);
        }
      }
    },
    setIndex(trees, parentIndex = '') {
      if(!trees) return;
      trees.forEach((tree, index) => {
        tree.currentIndex = index;
        tree.customIndex = `${parentIndex}${++index}`;
        tree.currentSort = index++;
        // tree.sortId = index;
        // 唯一标识
        tree.MID = `${tree.id}_${tree.customIndex}`;
        if(tree.children && tree.children.length > 0) {
          this.setIndex(tree.children, `${tree.customIndex}.`);
        }
      });
    },
    // 点击添加
    handleClickAdd() {
      this.$refs.materialDialogRef.openMaterialList();
    },
    // 点击删除
    handleClickDelete(row) {
      this.dataList.splice(row.currentIndex, 1);
      Platform.toast(this.$t('common.base.tip.deleteSuccess'), 'success');
      this.inputForValue(this.dataList);
    },
    // 过滤重复的数据
    filterDuplicateData(val) {
      if (!Array.isArray(val)) return;
      
      let map = new Map();
      for (let item of val) {
        if (!map.has(item.id)) {
          map.set(item.id, item);
        }
      }
      return [...map.values()];
    },
    // 点击保存
    handleSubmit(params) {
      let materialBill = [...(this.dataList || []), ...(params || [])];
      this.dataList = this.filterDuplicateData(materialBill);

      this.inputForValue(this.dataList);
    },
  },
};
</script>
<style lang="scss" scoped>
</style>
